package com.xhx.config;

import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

/**
 * MongoDB Primary Config
 */
@Configuration
@EnableMongoRepositories(basePackages = MongoPrimaryConfig.ENTITY_PACKAGE, mongoTemplateRef = "primaryMongoTemplate")
public class MongoPrimaryConfig {

    /**
     * 指定 Mapper 连接字符串
     */
    static final String DATASOURCE_PREFIX = "spring.data.mongodb.primary";

    /**
     * 指定 Mapper 接口类目录
     */
    static final String ENTITY_PACKAGE = "com.xhx.dao.mongodb";

    @Bean
    @Primary
    @ConfigurationProperties(prefix = DATASOURCE_PREFIX)
    public MongoProperties primaryMongoProperties() {
        return new MongoProperties();
    }

    @Primary
    @Bean(name = "primaryMongoTemplate")
    public MongoTemplate primaryMongoTemplate() throws Exception {
        return new MongoTemplate(primaryFactory(primaryMongoProperties()));
    }

    @Bean
    @Primary
    public MongoDatabaseFactory primaryFactory(MongoProperties mongoProperties) throws Exception {
//        ConnectionString connString = new ConnectionString(
//                //"mongodb+srv://<username>:<password>@<cluster-address>/test?w=majority"
//                //mongodb://primaryuser:Abcd1234@localhost:27017/primary
//                primaryMongoProperties().getUri()
//        );
        return new SimpleMongoClientDatabaseFactory(mongoProperties.getUri());
    }
}
